package com.spring.embed;

import com.spring.core.context.AbstractApplicationContext;
import com.spring.core.context.AnnotationApplicationContext;
import com.spring.core.context.ApplicationContext;
import com.spring.web.dispatch.DispatchServlet;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

/**
 * 内嵌Tomcat
 *
 * @author Zee
 * @version 1.0
 * @date 2021/10/12
 */

public class EmbedTomcat {

    public static void start(ApplicationContext context) {
        System.out.println("启动tomcat容器...");
        int port = Integer.parseInt(((AnnotationApplicationContext) context).getProperties().getProperty("spring.server.port"));
        String contextPath = ((AnnotationApplicationContext) context).getProperties().getProperty("spring.server.path");
        Tomcat tomcat = new Tomcat();
        // 设置Tomcat的端口号
        tomcat.setPort(port);
        // 是否设置Tomcat自动部署
        tomcat.getHost().setAutoDeploy(false);
        // 创建上下文
        StandardContext standardContext = new StandardContext();
        // 设置项目名
        standardContext.setPath(contextPath);
        // 监听上下文
        standardContext.addLifecycleListener(new Tomcat.FixContextListener());
        // 向tomcat容器对象添加上下文配置
        tomcat.getHost().addChild(standardContext);
        // 创建Servlet
        tomcat.addServlet(contextPath, "dispatch", new DispatchServlet(context));
        // Servlet映射
        standardContext.addServletMappingDecoded("/*", "dispatch");
        try {
            tomcat.start();
            //等待
            tomcat.getServer().await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

